package com.thread.example.handleList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实例2：
 *   List多线程并发读取读取现有的list对象
 */
public class Test_3 {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        Map<Long, Integer> map = new HashMap<Long, Integer>();
        for (int i = 0; i < 20; i++) {
            list.add("" + i);
        }
        //Java虚拟机的可用的处理器数量
        int pcount = Runtime.getRuntime().availableProcessors();
        long start = System.currentTimeMillis();

        for (int i = 0; i < pcount; i++) {
            Thread threadItem = new MyThread1(list, map);
            //一个线程 分配 一个处理器
            map.put(threadItem.getId(), Integer.valueOf(i));
            threadItem.start();
            try {
                threadItem.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // System.out.println(list.get(i));
        }
        System.out.println("-耗时---" + (System.currentTimeMillis() - start));
    }


    public static class MyThread1 extends Thread {

        private List<String> list;
        private Map<Long, Integer> map;

        public MyThread1(List<String> list, Map<Long, Integer> map) {
            this.list = list;
            this.map = map;
        }

        @Override
        public void run() {
            int pcount = Runtime.getRuntime().availableProcessors();
            int i = map.get(Thread.currentThread().getId());
            for (; i < list.size(); i += pcount) {
                System.out.println(list.get(i));
            }
        }
    }
}
